import React, { useEffect, useState } from 'react';
import { Modal, Form, Input, Select, Upload, Image, message, Tabs, InputNumber, Switch } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import { createGameContent, updateGameContent } from '@/services/learningContentApi';
import { uploadImage } from '@/services/systemManagementApi';

interface GameContentFormProps {
  visible: boolean;
  mode: 'create' | 'edit';
  initialValues?: LEARNING.GameContentModel;
  onCancel: () => void;
  onSuccess: () => void;
}

const GameContentForm: React.FC<GameContentFormProps> = ({
  visible,
  mode,
  initialValues,
  onCancel,
  onSuccess,
}) => {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [coverImageUrl, setCoverImageUrl] = useState<string>('');
  const [activeTab, setActiveTab] = useState('basic');

  useEffect(() => {
    if (visible) {
      if (mode === 'edit' && initialValues) {
        form.setFieldsValue(initialValues);
        setCoverImageUrl(initialValues.cover_image || '');
      } else {
        form.resetFields();
        setCoverImageUrl('');
      }
    }
  }, [visible, mode, initialValues, form]);

  // 处理表单提交
  const handleSubmit = async () => {
    try {
      const values = await form.validateFields();
      setLoading(true);

      const submitData = {
        ...values,
        cover_image: coverImageUrl,
      };

      if (mode === 'create') {
        await createGameContent(submitData);
        message.success('游戏内容创建成功');
      } else {
        await updateGameContent(initialValues!.id, submitData);
        message.success('游戏内容更新成功');
      }

      onSuccess();
    } catch (error) {
      message.error(mode === 'create' ? '游戏内容创建失败' : '游戏内容更新失败');
    } finally {
      setLoading(false);
    }
  };

  // 处理封面上传
  const handleCoverUpload = async (file: File) => {
    try {
      const response = await uploadImage(file);
      setCoverImageUrl(response.data.url);
      message.success('封面上传成功');
      return false;
    } catch (error) {
      message.error('封面上传失败');
      return false;
    }
  };

  const tabItems = [
    {
      key: 'basic',
      label: '基本信息',
      children: (
        <>
          <Form.Item
            name="title"
            label="游戏名称"
            rules={[
              { required: true, message: '请输入游戏名称' },
              { max: 100, message: '名称不能超过100个字符' },
            ]}
          >
            <Input placeholder="请输入游戏名称" />
          </Form.Item>

          <Form.Item
            name="description"
            label="游戏描述"
            rules={[
              { required: true, message: '请输入游戏描述' },
              { max: 500, message: '描述不能超过500个字符' },
            ]}
          >
            <Input.TextArea
              rows={4}
              placeholder="请输入游戏描述"
              showCount
              maxLength={500}
            />
          </Form.Item>

          <Form.Item label="游戏封面">
            <div style={{ display: 'flex', alignItems: 'center', gap: 16 }}>
              {coverImageUrl && (
                <Image
                  src={coverImageUrl}
                  alt="游戏封面"
                  width={120}
                  height={80}
                  style={{ objectFit: 'cover', borderRadius: 4 }}
                />
              )}
              <Upload
                showUploadList={false}
                beforeUpload={handleCoverUpload}
                accept="image/*"
              >
                <div style={{
                  width: 120,
                  height: 80,
                  border: '1px dashed #d9d9d9',
                  borderRadius: 4,
                  display: 'flex',
                  alignItems: 'center',
                  justifyContent: 'center',
                  cursor: 'pointer',
                }}>
                  <div style={{ textAlign: 'center' }}>
                    <PlusOutlined />
                    <div style={{ marginTop: 8, fontSize: '12px' }}>上传封面</div>
                  </div>
                </div>
              </Upload>
            </div>
          </Form.Item>

          <Form.Item
            name="type"
            label="游戏类型"
            rules={[{ required: true, message: '请选择游戏类型' }]}
          >
            <Select placeholder="请选择游戏类型">
              <Select.Option value="pronunciation">发音练习</Select.Option>
              <Select.Option value="vocabulary">词汇学习</Select.Option>
              <Select.Option value="grammar">语法练习</Select.Option>
              <Select.Option value="listening">听力训练</Select.Option>
              <Select.Option value="reading">阅读理解</Select.Option>
            </Select>
          </Form.Item>

          <Form.Item
            name="difficulty"
            label="难度等级"
            rules={[{ required: true, message: '请选择难度等级' }]}
          >
            <Select placeholder="请选择难度等级">
              <Select.Option value="easy">简单</Select.Option>
              <Select.Option value="medium">中等</Select.Option>
              <Select.Option value="hard">困难</Select.Option>
            </Select>
          </Form.Item>

          <Form.Item
            name="status"
            label="状态"
            rules={[{ required: true, message: '请选择状态' }]}
          >
            <Select placeholder="请选择状态">
              <Select.Option value="testing">测试中</Select.Option>
              <Select.Option value="active">启用</Select.Option>
              <Select.Option value="inactive">禁用</Select.Option>
            </Select>
          </Form.Item>
        </>
      ),
    },
    {
      key: 'content',
      label: '游戏内容',
      children: (
        <>
          <Form.Item
            name="game_rules"
            label="游戏规则"
            rules={[{ required: true, message: '请输入游戏规则' }]}
          >
            <Input.TextArea
              rows={6}
              placeholder="请输入游戏规则说明"
            />
          </Form.Item>

          <Form.Item
            name="game_config"
            label="游戏配置"
          >
            <Input.TextArea
              rows={8}
              placeholder="请输入游戏配置JSON，如关卡设置、题目配置等"
            />
          </Form.Item>

          <Form.Item
            name="instructions"
            label="操作说明"
          >
            <Input.TextArea
              rows={4}
              placeholder="请输入游戏操作说明"
            />
          </Form.Item>

          <Form.Item
            name="hints"
            label="提示信息"
          >
            <Input.TextArea
              rows={3}
              placeholder="请输入游戏提示信息"
            />
          </Form.Item>
        </>
      ),
    },
    {
      key: 'settings',
      label: '游戏设置',
      children: (
        <>
          <Form.Item
            name="estimated_duration"
            label="预计时长(分钟)"
          >
            <InputNumber
              style={{ width: '100%' }}
              placeholder="请输入预计游戏时长"
              min={1}
              max={120}
            />
          </Form.Item>

          <Form.Item
            name="max_score"
            label="最高分数"
          >
            <InputNumber
              style={{ width: '100%' }}
              placeholder="请输入游戏最高分数"
              min={1}
            />
          </Form.Item>

          <Form.Item
            name="min_pass_score"
            label="及格分数"
          >
            <InputNumber
              style={{ width: '100%' }}
              placeholder="请输入游戏及格分数"
              min={0}
            />
          </Form.Item>

          <Form.Item
            name="max_attempts"
            label="最大尝试次数"
          >
            <InputNumber
              style={{ width: '100%' }}
              placeholder="请输入最大尝试次数，0表示不限制"
              min={0}
            />
          </Form.Item>

          <Form.Item
            name="is_featured"
            label="是否推荐"
            valuePropName="checked"
          >
            <Switch />
          </Form.Item>

          <Form.Item
            name="allow_replay"
            label="允许重玩"
            valuePropName="checked"
          >
            <Switch />
          </Form.Item>

          <Form.Item
            name="show_leaderboard"
            label="显示排行榜"
            valuePropName="checked"
          >
            <Switch />
          </Form.Item>

          <Form.Item
            name="sort_order"
            label="排序权重"
          >
            <InputNumber
              style={{ width: '100%' }}
              placeholder="请输入排序权重，数字越小越靠前"
              min={0}
            />
          </Form.Item>

          <Form.Item
            name="tags"
            label="游戏标签"
          >
            <Select
              mode="tags"
              placeholder="请输入游戏标签"
              style={{ width: '100%' }}
            />
          </Form.Item>
        </>
      ),
    },
  ];

  return (
    <Modal
      title={mode === 'create' ? '新建游戏内容' : '编辑游戏内容'}
      open={visible}
      onCancel={onCancel}
      onOk={handleSubmit}
      confirmLoading={loading}
      width={800}
      destroyOnClose
    >
      <Form
        form={form}
        layout="vertical"
        initialValues={{
          type: 'pronunciation',
          difficulty: 'medium',
          status: 'testing',
          estimated_duration: 10,
          max_score: 100,
          is_featured: false,
          allow_replay: true,
          show_leaderboard: true,
          sort_order: 0,
        }}
      >
        <Tabs
          activeKey={activeTab}
          onChange={setActiveTab}
          items={tabItems}
        />
      </Form>
    </Modal>
  );
};

export default GameContentForm;
